﻿using System;
using AutoMapper;
using Framework.Exceptions;
using Interfaces.BusinessLogic;
using Interfaces.Models;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using ServiceInfrastructure.Models.NewsModels.Models;

namespace BusinessLogic.Services.Mapping
{
    public class FeedContractMapper : IEntityMapper<IFeed,Feed>
    {
        public Feed Map(IFeed entity)
        {
            Feed newFeed = null;

            try
            {
                CreateMapping();
                newFeed = Mapper.Map<IFeed, Feed>(entity);
            }
            catch (Exception exception)
            {
                if (ExceptionHandlingManager.HandleException(exception, PolicyNames.DALPolicy))
                    throw;
            }

            return newFeed;
        }

        private static void CreateMapping()
        {
            Mapper.Reset();
            Mapper.CreateMap<IFeed, Feed>()
                  .ConstructUsing((Func<ResolutionContext, Feed>)(obj => new Feed()));
            Mapper.CreateMap<INewsDataItem, NewsDataItem>()
                  .ForMember(src=>src.FeedId, opt=>opt.MapFrom(dest=>dest.SourceFeed.Id))
                  .ConstructUsing((Func<ResolutionContext, NewsDataItem>)(obj => new NewsDataItem()));
            Mapper.CreateMap<IPerson, Person>()
                  .ConstructUsing((Func<ResolutionContext, Person>)(obj => new Person()));
            Mapper.CreateMap<ICategory, Category>()
                 .ConstructUsing((Func<ResolutionContext, Category>)(obj => new Category()));
            Mapper.CreateMap<ILink, Link>()
                .ConstructUsing((Func<ResolutionContext, Link>)(obj => new Link()));
        }
    }
}
